//
//  EmoticonViewController.swift
//  03-表情键盘
//
//  Created by 房城鸿 on 15/10/18.
//  Copyright © 2015年 房兰峰. All rights reserved.
//

import UIKit

/// 表情键盘控制器 - 系统键盘默认高度是 216

private let EmoticonCellID = "EmoticonCellID"
class EmoticonViewController: UIViewController {
    
    /// 选中表情的闭包回调
    var selectedEmoticonCallBack:(emoticon:Emoticon)->()
    
    init(selectedEmoticon:(emoticon:Emoticon) ->()){
        
        selectedEmoticonCallBack = selectedEmoticon
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    ///  toolbar 的 监听方法
    ///
    ///  - parameter item:点击的 toolbar
    @objc private func clickItem(item:UIBarButtonItem){
    
        let indexPath = NSIndexPath(forRow: 0, inSection: item.tag)
        
        //让collectionView 滚动到对应位置
        collectionView.scrollToItemAtIndexPath(indexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: true)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.redColor()
        
        collectionView.backgroundColor = UIColor(white: 0.95, alpha: 1)
        
        //TODO: - 加载表情数据
        viewModel.loadPackages()
        
        setupUI()
        
    }
    
///  <#Description#>
    private func setupUI(){
    
        //添加控件
        view.addSubview(toolbar)
        view.addSubview(collectionView)
        
        
        //自动布局
        let viewDict = ["tb":toolbar,"cv":collectionView]
        toolbar.translatesAutoresizingMaskIntoConstraints = false
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[tb]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-0-[cv]-0-|", options: [], metrics: nil, views: viewDict))
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|-0-[cv]-[tb(44)]-0-|", options: [], metrics: nil, views: viewDict))
        
        //准备控件
        prepareToolbar()
        //添加colectionView
        prepareCollectionView()
        
    }
    ///  准备工具栏
    private func prepareToolbar(){

        toolbar.tintColor = UIColor.darkGrayColor()
        var items = [UIBarButtonItem]()
        
        var tagIndex = 0
        
        for title in viewModel.package{
        
            items.append(UIBarButtonItem(title:title.group_name_cn , style: UIBarButtonItemStyle.Plain, target: self, action: "clickItem:"))
            items.last?.tag = tagIndex++
            
            items.append(UIBarButtonItem(barButtonSystemItem: UIBarButtonSystemItem.FlexibleSpace, target: nil, action: nil))
            
        }
        items.removeLast()
        
        toolbar.items = items
    
    }
    
    //准备collectionView
    private func prepareCollectionView(){
    
        //1.注册cell
        collectionView.registerClass(EmoticonCell.self, forCellWithReuseIdentifier: EmoticonCellID)
        //2.指定数据源
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    //MARK: - 懒加载控件
    ///工具栏
    private lazy var toolbar = UIToolbar()
    /// collectionView
    private lazy var collectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: EmoticonLayout())
    
    /// 表情包的视图模型
    private lazy var viewModel = EmoticonViewModel()
}

/// layout   的布局
private class EmoticonLayout:UICollectionViewFlowLayout{
    
    //1. 会调用一次，在收到消息，当布局被重新设置的时候会调用
    //2. 一定要重写父类的  super
    ///  准备布局，第一次使用的时候会被调用 - collectionView 的大小已经去顶，已经完成布局
    /// 会在数据源 cell 的个数前调用，可以再次准百 layout  的属性
    private override func prepareLayout() {
        super.prepareLayout()
//        print(collectionView)  //frame = (0 0; 375 172)  
        
        // 设置属性
        let w = collectionView!.bounds.width / 7
        // 切记： 这里如果要适配 iphone5 需要把下面的 0.5  改成 0.499
        // 如果适配iphone5 会每页显示  2行，因为浮点数计算有偏差
        let margin = (collectionView!.bounds.height - 3*w) * 0.499
        itemSize = CGSize(width: w, height: w)
        
        minimumInteritemSpacing = 0
        minimumLineSpacing = 0
        sectionInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        
        scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
    }
    
}

// MARK: - 数据源方法
extension EmoticonViewController:UICollectionViewDataSource , UICollectionViewDelegate{

    ///  分组的数量
    func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
        return viewModel.package.count
    }
    
    ///  每个section 对应表情中包含的表情数量
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return  viewModel.package[section].emoticons.count
    }
    
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(EmoticonCellID, forIndexPath: indexPath) as! EmoticonCell
        
//        cell.backgroundColor = (indexPath.item % 2 == 0) ? UIColor.redColor() : UIColor.blueColor()
    
        cell.emoticon = viewModel.emoticon(indexPath)
        return cell
    }
    
    ///  选中cell 的代理方法
    func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        
        /// 执行闭包回调
        selectedEmoticonCallBack(emoticon: viewModel.emoticon(indexPath))
    }

}

///  表情cell
private class EmoticonCell:UICollectionViewCell{
    
    /// 表情包对应的表情索引
    var emoticon: Emoticon? {
        didSet{
            //以下两个清空的动作，能够解决重用的问题
            //1，设置图片 ，如果没有会清空图片
            emoticonButton.setImage(UIImage(contentsOfFile: emoticon!.imagePath), forState: UIControlState.Normal)
            
            //2. 设置文字 - 如果没有会清空文字
            emoticonButton.setTitle(emoticon?.emoji, forState: UIControlState.Normal)
            
            if emoticon!.isRemove{
                
                 emoticonButton.setImage(UIImage(named: "compose_emotion_delete"), forState: UIControlState.Normal)
                emoticonButton.setImage(UIImage(named: "compose_emotion_delete_highlighted"), forState: UIControlState.Highlighted)
                
            }
        }
    }
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }
    
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func setupUI(){
    
        //1. 添加控件
        contentView.addSubview(emoticonButton)
//        emoticonButton.backgroundColor = UIColor.whiteColor()
        
        //2. 自动布局
        emoticonButton.frame = bounds
        
        //返回相同中心点的矩形
        emoticonButton.frame = CGRectInset(bounds, 4, 4)
        
        //设置字体
        emoticonButton.titleLabel?.font = UIFont.systemFontOfSize(32)
        
        emoticonButton.userInteractionEnabled = false
    }
    
    //MARK: - 懒加载控件
    private lazy var emoticonButton:UIButton = UIButton()
    
}



